package com.tanjie.blackbean.core.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.tree.Tree;

import java.util.List;
import java.util.function.Function;

/**
 * @author: tanjie
 * @date: 2021-11-25
 **/
public abstract class BeanProcessUtil {

    private BeanProcessUtil() {
    }

    /**
     * 从一棵树中过滤出指定节点id的子树集合
     *
     * @param allTreeList 完整的树
     * @param topIdList   需要过滤出来的节点id
     * @param results     将过滤结果存放到这个集合中
     */
    public static void recursionFilter(List<Tree<String>> allTreeList, List<String> topIdList, List<Tree<String>> results) {
        for (Tree<String> tree : allTreeList) {
            String treeId = tree.getId();
            if (topIdList.contains(treeId)) {
                results.add(tree);
            }
            List<Tree<String>> children = tree.getChildren();
            if (CollectionUtil.isNotEmpty(children)) recursionFilter(children, topIdList, results);
        }
    }

    public static <T> T cloneObject(Object source, Class<T> tClass) {
        if (source == null) {
            return null;
        }
        try {
            T t = tClass.newInstance();
            BeanUtil.copyProperties(source, t);
            return t;
        } catch (InstantiationException | IllegalAccessException e) {
            return null;
        }
    }

    public static <P, V> V cloneConvertObject(P p, Class<V> tClass, Function<P, V> convertFunction) {
        if (p == null) {
            return null;
        }
        try {
            V v = tClass.newInstance();
            BeanUtil.copyProperties(p, v);
            if (convertFunction != null) {
                return convertFunction.apply(p);
            }
            return v;
        } catch (InstantiationException | IllegalAccessException e) {
            return null;
        }
    }

}